package com.ajocer.springbootinit.controller;

import com.ajocer.springbootinit.common.BaseResponse;
import com.ajocer.springbootinit.common.ResultUtils;
import com.ajocer.springbootinit.monitor.CachePerformanceMonitor;
import com.ajocer.springbootinit.rag.MultiLayerCacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 监控控制器
 * 提供系统性能监控数据
 */
@RestController
@RequestMapping("/monitor")
@Slf4j
public class MonitorController {

    @Autowired
    private CachePerformanceMonitor performanceMonitor;
    
    @Autowired
    private MultiLayerCacheService cacheService;
    
    /**
     * 获取缓存性能统计信息
     */
    @GetMapping("/cache/stats")
    public BaseResponse<Map<String, Object>> getCacheStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 缓存命中率
        stats.put("cacheHitRate", String.format("%.2f%%", performanceMonitor.getCacheHitRate() * 100));
        
        // 平均查询延迟
        stats.put("averageLatency", String.format("%.2f ms", performanceMonitor.getAverageLatency()));
        
        // API成本节省率
        stats.put("apiCostSavingRate", String.format("%.2f%%", performanceMonitor.getApiCostSavingRate() * 100));
        
        // 本地缓存统计
        stats.put("localCacheStats", cacheService.getCacheStats());
        
        return ResultUtils.success(stats);
    }
    
    /**
     * 获取系统健康状态
     */
    @GetMapping("/health")
    public BaseResponse<Map<String, Object>> getHealthStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("status", "UP");
        status.put("averageLatency", String.format("%.2f ms", performanceMonitor.getAverageLatency()));
        
        // 判断系统是否健康
        boolean isHealthy = performanceMonitor.getAverageLatency() < 10.0; // 平均延迟小于10ms认为健康
        
        if (isHealthy) {
            status.put("message", "系统运行正常，平均查询延迟在目标范围内");
        } else {
            status.put("message", "系统性能需要优化，平均查询延迟超出目标范围");
        }
        
        return ResultUtils.success(status);
    }
} 